<script setup lang="ts">
import { ref, onMounted } from "vue";
import BetterScroll from "better-scroll";

let scroll: any = {};


let scrollHeight = 0;

const wrapperRef = ref(null);

const props = defineProps({
  probeType: {
    type: Number,
    default: 0,
  },
  pullUpLoad: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["scroll", "scrollEnd", "pullingUp"]);

onMounted(() => {
  const wrapper: any = wrapperRef.value;

  // 创建scroll
  scroll = new BetterScroll(wrapper, {
    // 0-1：不打印滚动位置，2：打印位置，但不打印惯性滑动的滚动位置，3：打印手指离开后的惯性滚动位置
    probeType: props.probeType,
    // 设置非 button 上的元素是否可以发生点击事件
    click: true,
    pullUpLoad: true,
    // pullUpLoad: {
    //     // 可以配置顶部下拉的距离（threshold）决定刷新时机
    //   threshold: -20,
    // },
  });

  scrollHeight = scroll.scrollerHeight;  

  // 监听滚动的位置
  if (props.probeType === 2 || props.probeType === 3) {
    scroll.on("scroll", (position: any) => {
      emit("scroll", position);
    });

    scroll.on("scrollEnd", (endPosition: any) => {
      emit("scrollEnd", endPosition);
    });
  }
  // 监听上拉事件
  if (props.pullUpLoad)
    scroll.on("pullingUp", () => {
      emit("pullingUp");
    });
});

function scrollTo(x: number, y: number, time = 300) {
  scroll && scroll.scrollTo(x, y, time);
}
function finishPullUp() {
  // 等数据请求完成，并且新的数据展示完成后，刷新pullup使下次pullup可以生效
  setTimeout(() => {
    scroll && scroll.finishPullUp(); // 该函数一调用就可以立即触发下一次，所以可以搞个延时setTimeout
  }, 1000);
}
function refresh() {
  scroll && scroll.refresh();
}
function getScrollY() {
  return scroll ? scroll.y : 0;
}

defineExpose({
  scrollHeight,
  refresh,
  finishPullUp,
  scrollTo,
});
</script>

<template>
  <div class="scroll" ref="wrapperRef">
    <slot></slot>
  </div>
</template>

<style lang="less"></style>
